Page({
  data: {
    orderList: [],
    paidOrders: [],
    completedOrders: [],
    stats: {
      total_orders: 0,
      total_amount: '0.00',
      paid_orders: 0,
      completed_orders: 0
    }
  },
  onLoad() {
    this.getOrderList();
    this.getTodayStats();
  },
  onShow() {
    this.getOrderList();
    this.getTodayStats();
  },
  getOrderList() {
    wx.request({
      url: 'http://localhost:3000/api/order/admin',
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 0) {
          const orderList = res.data.data;
          const paidOrders = orderList.filter(o => o.status === '已支付');
          const completedOrders = orderList.filter(o => o.status === '已完成');
          this.setData({ orderList, paidOrders, completedOrders });
        }
      }
    });
  },
  getTodayStats() {
    wx.request({
      url: 'http://localhost:3000/api/order/stats/today',
      method: 'GET',
      success: (res) => {
        if (res.data && res.data.code === 0) {
          this.setData({ stats: res.data.data });
        }
      }
    });
  },
  completeOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认完成',
      content: '确定要将此订单标记为已完成吗？',
      success: (res) => {
        if (res.confirm) {
          wx.request({
            url: 'http://localhost:3000/api/order/complete',
            method: 'POST',
            data: { order_id: orderId },
            success: (res) => {
              if (res.data && res.data.code === 0) {
                wx.showToast({ title: '订单已完成', icon: 'success' });
                this.getOrderList();
                this.getTodayStats();
              } else {
                wx.showToast({ title: res.data.message || '操作失败', icon: 'none' });
              }
            },
            fail: () => {
              wx.showToast({ title: '操作失败', icon: 'none' });
            }
          });
        }
      }
    });
  },
  viewDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/user/order/detail?id=' + orderId
    });
  },
  goBack() {
    wx.navigateBack();
  }
}); 